<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 角色管理 -->
            <el-button
              style="margin-bottom: 20px;"
              type="primary"
              @click="showDialog = true"
            >+ 新增角色</el-button>
            <el-table
              :data="list"
              style="width: 100%"
              border
            >
              <!--
                表格的一列
                  label: 表头
                  width: 指定宽度
                  prop: 用于指定该列应该显示什么数据
              -->
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="100"
                :index="indexFn"
              />
              <el-table-column
                align="center"
                label="角色名"
                prop="name"
                width="200"
              />
              <el-table-column
                label="描述"
                prop="description"
              />
              <el-table-column width="200" align="center" label="操作">
                <template v-slot="{row}">
                  <el-button type="text" @click="showAssign(row)">分配权限</el-button>
                  <el-button type="text" @click="showUpdate(row)">修改</el-button>
                  <el-button type="text" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="end" style="margin-top: 10px;">
              <!--
                background:分页带有背景
                total： 总共有多少条数据
                page-size: 每页显示多少条
                current-page: 当前页
                -->
              <el-pagination
                layout="prev, pager, next"
                background
                :total="total"
                :page-size="pagesize"
                :current-page="page"
                @current-change="changeFn"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- 公司的信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="company.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="company.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="company.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="company.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增角色弹窗 -->
      <el-dialog
        :title="form.id ? '修改角色':'新增角色'"
        :visible="showDialog"
        width="30%"
        @close="close"
      >
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </template>
      </el-dialog>
      <el-dialog width="30%" title="分配权限" :visible.sync="showAssignDialog">
        <el-tree
          ref="tree"
          :data="permissionList"
          :props="defaultProps"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <template #footer>
          <el-button @click="showAssignDialog=false">取消</el-button>
          <el-button type="primary" @click="assign">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addRole, assignPermission, delRole, editRole, getCompanyInfo, getRoleDetail, getRoleList } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role',
      list: [],
      total: 0,
      pagesize: 5,
      page: 1,
      loading: false,
      form: {
        name: '',
        // 添加角色的接口文档有误， 描述叫description
        description: ''
      },
      showDialog: false,
      rules: {
        name: [
          { required: true, message: '请输入角色名称' }
        ],
        description: [
          { required: true, message: '请输入角色描述' }
        ]
      },
      company: {},
      showAssignDialog: false,
      // 权限列表
      permissionList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 当前角色的id
      roleId: ''
    }
  },
  // watch: {
  //   activeName(value) {
  //     console.log('数据发生了改变')
  //   }
  // },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const data = await getRoleList(this.page, this.pagesize)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    changeFn(value) {
      // console.log('发生了改变', value)
      // 修改当前页
      this.page = value
      // 重新发送请求
      this.getRoleList()
    },
    indexFn(index) {
      // 需要加上前面的页数 * 每页的条数
      return index + 1 + (this.page - 1) * this.pagesize
    },
    async del(id) {
      // console.log(id)
      try {
        await this.$confirm('亲，你确定要删除该角色吗', '温馨提示', { type: 'warning' })
      } catch {
        return
      }

      // 发送请求，进行删除
      await delRole(id)

      this.$message.success('删除角色成功')
      // 重新渲染
      if (this.list.length === 1) {
        // 当前页只有1条数据
        this.page--
      }
      this.getRoleList()
    },
    close() {
      this.showDialog = false
      // 重置数据
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    async addRole() {
      // 1. 对整个表单进行校验
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      // 发送请求添加
      if (this.form.id) {
        await editRole(this.form)
      } else {
        await addRole(this.form)
        // 把page改为最后一页 30
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
      }
      // 提示消息
      this.$message.success('操作成功')
      // 重新渲染
      this.getRoleList()
      // 关闭弹窗
      this.showDialog = false
    },
    showUpdate(row) {
      this.showDialog = true
      // 1. 发送请求 或者 直接使用row中的数据
      this.form = { ...row }
    },
    async getCompanyInfo() {
      const data = await getCompanyInfo(this.$store.state.user.userInfo.companyId)
      // console.log(data)
      this.company = data
    },
    async showAssign(row) {
      this.showAssignDialog = true
      const data = await getPermissionList()
      this.permissionList = listToTree(data, '0')
      // 发送请求，获取角色已有的权限信息
      const { permIds } = await getRoleDetail(row.id)
      console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
      // 保存当前角色id
      this.roleId = row.id
    },
    async assign() {
      // 1. 获取到选中的权限的列表
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPermission(this.roleId, permIds)

      this.$message.success('分配权限成功')
      this.showAssignDialog = false
    }
  }
}
</script>

<style>

</style>
